using RabbitMQ.Client;

namespace Aurora.RabbitMq.Provider;

/// <summary>
/// channel pool 子项
/// </summary>
public class ChannelPoolItem : IDisposable
{
    public IModel Channel { get; }

    public ChannelPoolItem(IModel channel)
    {
        Channel = channel;
    }

    private volatile bool _isInUse;

    public bool IsInUse
    {
        get => _isInUse;
        set => _isInUse = value;
    }

    public void Acquire()
    {
        lock (this)
        {
            while (IsInUse)
            {
                Monitor.Wait(this);
            }

            IsInUse = true;
        }
    }


    public void WaitIfInUse(TimeSpan timeout)
    {
        lock (this)
        {
            while (!IsInUse)
            {
                return;
            }

            Monitor.Wait(this, timeout);
        }
    }

    public void Release()
    {
        lock (this)
        {
            IsInUse = false;
            Monitor.PulseAll(this);
        }
    }

    public void Dispose()
    {
        Channel.Dispose();
    }
}